﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Events.Data;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;

namespace Events.Worker
{
	public class WorkerRole : RoleEntryPoint
	{
		public override void Run()
		{
			// This is a sample worker implementation. Replace with your logic.
			Trace.WriteLine("Events.Worker entry point called", "Information");

			CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
			{
				configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
			});

			var storageAccount = CloudStorageAccount.FromConfigurationSetting("BlobStorageConnectionString");
			var queueStorage = storageAccount.CreateCloudQueueClient();
			var queue = queueStorage.GetQueueReference("registrationqueue");
			queue.CreateIfNotExist();

			while (true)
			{
				var msg = queue.GetMessage(TimeSpan.FromSeconds(15));
				if (msg != null)
				{
					try
					{
						Trace.WriteLine(msg.AsString);
						var missionId = new Guid(msg.AsString);
						using (var context = HelfenHelfenEntities.Create())
						{
							context.SendRegistrationConfirmation(missionId);
						}

						queue.DeleteMessage(msg);
					}
					catch (Exception)
					{
						if (msg.DequeueCount > 1)
						{
							// Remove poisened message
							queue.DeleteMessage(msg);
						}
					}
				}
				else
				{
					Trace.WriteLine("No message, waiting...");
					Thread.Sleep(1000);
				}
			}
		}

		public override bool OnStart()
		{
			// Set the maximum number of concurrent connections 
			ServicePointManager.DefaultConnectionLimit = 12;

			var config = DiagnosticMonitor.GetDefaultInitialConfiguration();
			config.DiagnosticInfrastructureLogs.ScheduledTransferLogLevelFilter = LogLevel.Error;
			config.DiagnosticInfrastructureLogs.ScheduledTransferPeriod = TimeSpan.FromMinutes(2);
			Microsoft.WindowsAzure.Diagnostics.CrashDumps.EnableCollection(true);
			Microsoft.WindowsAzure.Diagnostics.CrashDumps.EnableCollection(false);
			config.WindowsEventLog.DataSources.Add("Application!*");
			config.WindowsEventLog.ScheduledTransferPeriod = TimeSpan.FromMinutes(1.0);
			config.Logs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1.0);
			DiagnosticMonitor.Start("DiagnosticsConnectionString", config); 

			// For information on handling configuration changes
			// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
			RoleEnvironment.Changing += RoleEnvironmentChanging;

			return base.OnStart();
		}

		private void RoleEnvironmentChanging(object sender, RoleEnvironmentChangingEventArgs e)
		{
			// If a configuration setting is changing
			if (e.Changes.Any(change => change is RoleEnvironmentConfigurationSettingChange))
			{
				// Set e.Cancel to true to restart this role instance
				e.Cancel = true;
			}
		}
	}
}
